package net.lb.socketserver.handler.impl.auth;

import javax.annotation.Resource;
import net.lb.baseutil.StringUtil;
import net.lb.baseutil.encrypt.RSAUtil;
import net.lb.socketserver.bus.BusinessCommand;
import net.lb.socketserver.bus.Message;
import net.lb.socketserver.handler.MessageHandler;
import net.lb.socketserver.handler.impl.auth.des.RandomKeyGenerater;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Resource
public class AuthHandler implements MessageHandler
{
    @Resource
    private RandomKeyGenerater keyGenerator;
    private byte[]             publicKey;
    private Logger             logger = LogManager.getLogger();
    
    @Override
    public byte interestedDataPacketType()
    {
        return BusinessCommand.AUTH;
    }
    
    @Override
    public void handler(Message message)
    {
        byte[] key = keyGenerator.generateRandomKey();
        message.getChannelInfo().setKey(key);
        RSAUtil rsaUtil = new RSAUtil();
        rsaUtil.setPublicKey(publicKey);
        byte[] result = rsaUtil.encrypt(key);
        if (logger.isDebugEnabled())
        {
            logger.debug("给予通道{}的密钥为{}", message.getChannelInfo().getAddress(), StringUtil.toHexString(key));
        }
        message.getBusinessData().clear().putArray(result).startRead(0);
        message.setResult(true);
        message.getChannelInfo().authMsg();
    }
    
    public void setPublicKey(byte[] publicKey)
    {
        this.publicKey = publicKey;
    }
}
